<template>
  <!-- !楼宇内容 -->
  <div class="build-info">
    <section class="header">
      <a-page-header style="padding: 10px 16px 0 16px" :backIcon="false">
        <template #title>
          <a-space>
            <BlIcon type="tree-louyu" />
            <span>{{ buildDetail.build_name }}</span>
          </a-space>
        </template>
        <template #extra>
          <a-space>
            <a-button
              danger
              @click="onBuildRemove"
              v-permission="['buildList', 'curd', 'delete']"
            >
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
            <a-button
              type="primary"
              ghost
              @click="onBuildEdit"
              v-permission="['buildList', 'curd', 'edit']"
            >
              <template #icon>
                <FormOutlined />
              </template>
              编辑
            </a-button>
            <a-button type="primary" ghost @click="onLayerManage">
              <template #icon>
                <BlIcon type="tree-louceng" />
              </template>
              楼层管理
            </a-button>
          </a-space>
        </template>
      </a-page-header>
      <a-menu
        mode="horizontal"
        :selectedKeys="[currentMenu.id]"
        @select="onMenuSelect"
      >
        <a-menu-item v-for="item of menuList" :key="item.id">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </section>
    <section class="content">
      <template v-if="!pageLoading">
        <!-- 房态管理 -->
        <RoomState
          v-show="currentAlias == 'buildDrawing'"
          showType="build"
          :villageId="villageId"
          :buildId="buildId"
        />
        <!-- 楼宇概况 -->
        <Overview
          v-if="currentAlias == 'buildRent'"
          :detail="buildDetail"
          type="build"
        />
        <!-- 楼宇信息 -->
        <BuildContent
          v-if="currentAlias == 'buildInfo'"
          :detail="buildDetail"
        />

        <!-- 应用页面 -->
        <template v-for="appMenu of loadedAppMenu" :key="appMenu.id">
          <micro-app-org
            v-show="appMenu.app == currentAppName && appMenu.mounted"
            router-mode="state"
            style="height: 100%"
            :name="appMenu.app + appMenu.arrKey"
            :url=" isProduction ? `${locationUrl}/micro_apps/${appMenu.app}/` : devHttpMap[currentAppName] "
            :default-page="`#${defaultPageData[currentAppName]}`"
            :data=" $utils.getAppToChildData({ loadInfo: { villageId, buildId } }) "
            @mounted="appMenu.mounted = true"
            @datachange="(e) => {handlePageChange(e)}"
          ></micro-app-org>
          <div class="spin-box" v-if="appMenu.app == currentAppName && !appMenu.mounted">
            <a-spin tip="加载中...">
            </a-spin>
          </div>
        </template>
      </template>
    </section>
    <!-- 楼宇编辑 -->
    <BuildEdit
      :visible="editVisible"
      :id="buildId"
      :villageId="villageId"
      @cancel="editVisible = false"
      @success="onBuildEditSuccess"
    />
    <!-- 楼层管理 -->
    <LayerManage
      :visible="layerVisible"
      :buildId="buildId"
      :villageId="villageId"
      @cancel="onLayerManageClose"
    />
  </div>
</template>
<script>
import {defineComponent, onBeforeUnmount, reactive, toRefs, watch} from "vue";
import { DeleteOutlined, FormOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import request from "../../common/utils/request";
import { BlIcon } from "bl-common-vue3";
import utils from "../../common/utils/utils";
import { MAIN_APP_NAMES } from "../../micro_apps/index";

// 楼宇编辑
import BuildEdit from "../../views/village/BuildingManage/modules/BuildingEdit.vue";
// 楼层管理
import LayerManage from "../../views/village/BuildingManage/modules/LayerManage.vue";

// 房态管理
import RoomState from "./modules/RoomState.vue";
// 楼宇概况
import Overview from "./modules/Overview.vue";
// 楼宇信息
import BuildContent from "./modules/BuildContent.vue";
import microApp from "@micro-zoe/micro-app";

// 渲染的组件映射 alias => components
const APP_COMPONENTS_MAP = {
  buildPropertyInfo: "villagePropertyInfo",
  buildWorkOrderInfo: "villageWorkOrderInfo",
  buildEnergyInfo: "villageEnergyInfo",
  buildIotInfo: "villageIotInfo",
};

export default defineComponent({
  name: "BuildInfo",
  components: {
    RoomState,
    Overview,
    BuildContent,
    BlIcon,
    DeleteOutlined,
    FormOutlined,
    BuildEdit,
    LayerManage,
  },
  props: {
    // 展示类型 modal弹层展示 page页面内展示
    showType: {
      type: String,
      default: "modal",
    },
    // 项目id
    villageId: {
      type: Number,
      default: 0,
    },
    // 楼宇id
    buildId: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      pageLoading: false,
      // 菜单
      menuList: [],
      currentMenu: {},
      // 楼宇详情
      buildDetail: {},
      editVisible: false,
      layerVisible: false,
      // 展示应用页面
      showMicroPages: false,
      currentAppName: "",
      currentAlias: "",
      loadedAppMenu: [],
      currentAppComponent: "",
    });

    /** 编辑楼宇 */
    const onBuildEdit = () => {
      state.editVisible = true;
    };
    const onBuildEditSuccess = () => {
      state.editVisible = false;
      getBuildDetail(true);
    };
    /** 删除楼宇 */
    const onBuildRemove = () => {
      utils.modalConfirm({
        content: "确认删除本楼宇吗？",
        centered: true,
        okType: "danger",
        onOk: () => {
          request
            .del("/village", "/project/build", {
              village_id: props.villageId,
              id: props.buildId,
              needMsg: true,
            })
            .then((res) => {
              message.success(res.msg || "删除成功");
              emit("remove");
            });
        },
      });
    };
    /** 楼层管理 */
    const onLayerManage = () => {
      state.layerVisible = true;
    };
    const onLayerManageClose = () => {
      state.layerVisible = false;
      emit("layerChange");
    };

    /** 菜单选中 */
    const onMenuSelect = (menu) => {
      const { key } = menu;
      state.currentMenu = state.menuList.find((item) => item.id == key);
      if (
        !state.currentMenu.app ||
        MAIN_APP_NAMES.includes(state.currentMenu.app)
      ) {
        // 主应用内菜单
        state.currentAppName = "";
        state.currentAlias = state.currentMenu.alias;
        state.currentAppComponent = "";
      } else {
        // 显示子应用内容
        state.currentAppName = state.currentMenu.app;
        state.currentAlias = `${state.currentMenu.alias}?villageId=${props.villageId}&buildId=${props.buildId}`;
        const index = state.loadedAppMenu.findIndex(
          (it) => it.id == state.currentMenu.id
        );
        if (index == -1) {
          state.loadedAppMenu.push(state.currentMenu);
        }
        state.currentAppComponent =
          APP_COMPONENTS_MAP[state.currentMenu.alias] ||
          state.currentMenu.alias;
      }
    };

    /** 获取导航菜单 */
    const getMenuList = () => {
      if (state.menuList.length) {
        onMenuSelect({ key: state.menuList[0].id });
        return;
      }
      request
        .get("/village", "/rentControl/menuList", {
          menu_type: "build",
        })
        .then((res) => {
          state.menuList = res.list;
          onMenuSelect({ key: state.menuList[0].id });
        });
    };

    /** 获取项目详情 */
    const getBuildDetail = (refresh = false) => {
      request
        .get("/village", "/project/build/get", {
          village_id: props.villageId,
          id: props.buildId,
          more: 1,
        })
        .then((res) => {
          state.buildDetail = res.detail;
          if (refresh) {
            emit("onChange", {
              name: state.buildDetail.build_name,
              detail: state.buildDetail,
            });
          }
        })
        .finally(() => {
          state.pageLoading = false;
        });
    };

    const handlePageChange = (e) => {
      const data = e?.detail?.data;
      window.microApp.forceDispatch({
        ...data,
      });
    };

    const locationUrl = location.origin;

    const devHttpMap = {
      org: "http://localhost:4001/",
      workVisitor: "http://localhost:4005/",
      workNotice: "http://localhost:4006/",
      workPark: "http://localhost:4007/",
      workEnergy: "http://localhost:4008/",
      workProperty: "http://localhost:4009/",
      workApproval: "http://localhost:4010/",
      workTask: "http://localhost:4011/",
      workSchedule: "http://localhost:4012/",
      workOrder: "http://localhost:4013/",
      workMeetingRoom: "http://localhost:4014/",
      workPatrol: "http://localhost:4015/",
      workCuPage: "http://localhost:4016/",
      workIOT: "http://localhost:4017/",
      workThird: "http://localhost:4018/",
      workForum: "http://localhost:4019/",
      shop: "http://localhost:4020/",
      workAI: "http://localhost:4021/",
      workWiki: "http://localhost:4022/",
      workHr: "http://localhost:4023/",
      workMail: "http://localhost:4024/",
      thirdSichuanPolice: "http://localhost:4025/",
    };

    const defaultPageData = {
      workProperty: "/property/Inventory",
      workOrder: "/order/workOrderDynamics",
      workIOT: "/main/villageIotInfo",
      workEnergy: "/energyConsumption",
    };

    const isProduction = !utils.isEnv();

    const UnloadApp = () => {
      state.loadedAppMenu.forEach((item) => {
        microApp.unmountApp(item.app + item.arrKey, { destroy: true, clearAliveState: true })
      });
    };

    const init = () => {
      UnloadApp()
      if (!props.buildId) {
        return;
      }
      state.pageLoading = true;
      getMenuList();
      getBuildDetail();
    };

    onBeforeUnmount(() => {
      UnloadApp();
    });

    watch(
      () => props.buildId,
      () => {
        init();
      }
    );

    init();

    return {
      ...toRefs(state),
      onMenuSelect,
      onBuildEdit,
      onBuildRemove,
      onLayerManage,
      onBuildEditSuccess,
      onLayerManageClose,
      defaultPageData,
      devHttpMap,
      locationUrl,
      isProduction,
      handlePageChange,
    };
  },
});
</script>
<style lang="less" scoped>
.build-info {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    padding: 8px;
    overflow: hidden auto;
    background-color: #f7f7f7;
      .spin-box {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
  }
}
</style>
